<template>
  <div class="permit-execution">
    <div class="page-container">
      <div class="page-header">
        <h2>执行中作业</h2>
        <div class="header-actions">
          <el-button type="primary" @click="goToApply">
            <el-icon><Plus /></el-icon>
            新建申请
          </el-button>
          <el-button @click="refreshList">
            <el-icon><Refresh /></el-icon>
            刷新
          </el-button>
        </div>
      </div>
      
      <!-- 筛选条件 -->
      <el-card class="filter-card">
        <el-form :model="searchForm" inline>
          <el-form-item label="作业类型">
            <el-select v-model="searchForm.workType" placeholder="全部类型" clearable>
              <el-option label="全部" value="" />
              <el-option label="高空作业" value="high_altitude" />
              <el-option label="动火作业" value="hot_work" />
              <el-option label="电气作业" value="electrical" />
              <el-option label="受限空间" value="confined_space" />
              <el-option label="起重作业" value="lifting" />
            </el-select>
          </el-form-item>
          
          <el-form-item label="作业地点">
            <el-input
              v-model="searchForm.location"
              placeholder="请输入作业地点"
              clearable
            />
          </el-form-item>
          
          <el-form-item label="执行状态">
            <el-select v-model="searchForm.status" placeholder="全部状态" clearable>
              <el-option label="全部" value="" />
              <el-option label="准备中" value="preparing" />
              <el-option label="执行中" value="executing" />
              <el-option label="暂停" value="paused" />
              <el-option label="即将超期" value="expiring" />
            </el-select>
          </el-form-item>
          
          <el-form-item>
            <el-button type="primary" @click="handleSearch">
              <el-icon><Search /></el-icon>
              搜索
            </el-button>
            <el-button @click="handleReset">
              <el-icon><Refresh /></el-icon>
              重置
            </el-button>
          </el-form-item>
        </el-form>
      </el-card>
      
      <!-- 执行列表 -->
      <el-card>
        <el-table
          v-loading="loading"
          :data="tableData"
          stripe
          border
        >
          <el-table-column prop="permitNumber" label="许可证编号" width="150" />
          <el-table-column prop="workType" label="作业类型" width="120">
            <template #default="{ row }">
              <el-tag :type="getWorkTypeTagType(row.workType)">
                {{ getWorkTypeLabel(row.workType) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="location" label="作业地点" width="200" />
          <el-table-column prop="applicant" label="申请人" width="100" />
          <el-table-column prop="startTime" label="开始时间" width="160" />
          <el-table-column prop="endTime" label="结束时间" width="160" />
          <el-table-column prop="status" label="执行状态" width="120">
            <template #default="{ row }">
              <el-tag :type="getStatusTagType(row.status)">
                {{ getStatusLabel(row.status) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="progress" label="进度" width="120">
            <template #default="{ row }">
              <el-progress :percentage="row.progress" :status="getProgressStatus(row.progress)" />
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200" fixed="right">
            <template #default="{ row }">
              <el-button type="primary" size="small" @click="handleView(row)">
                查看详情
              </el-button>
              <el-button type="warning" size="small" @click="handleExtend(row)">
                申请延期
              </el-button>
              <el-button type="success" size="small" @click="handleClose(row)">
                申请关闭
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        
        <!-- 分页 -->
        <div class="pagination-container">
          <el-pagination
            v-model:current-page="pagination.page"
            v-model:page-size="pagination.size"
            :total="pagination.total"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-card>
    </div>
    
    <!-- 许可证详情对话框 -->
    <PermitDetailDialog
      v-model="detailDialogVisible"
      :permit-data="currentPermit"
      @extend="handleExtendFromDetail"
      @close="handleCloseFromDetail"
    />
    
    <!-- 延期申请对话框 -->
    <ExtendDialog
      v-model="extendDialogVisible"
      :permit-data="currentPermit"
      @success="handleExtendSuccess"
    />
    
    <!-- 关闭申请对话框 -->
    <CloseDialog
      v-model="closeDialogVisible"
      :permit-data="currentPermit"
      @success="handleCloseSuccess"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import PermitDetailDialog from './components/PermitDetailDialog.vue'
import ExtendDialog from './components/ExtendDialog.vue'
import CloseDialog from './components/CloseDialog.vue'

const router = useRouter()

interface ExecutionItem {
  id: number
  permitNumber: string
  workType: string
  location: string
  applicant: string
  startTime: string
  endTime: string
  status: string
  progress: number
  workContent: string
  safetyMeasures: string[]
  personnel: any[]
  gasDetectors: any[]
}

const loading = ref(false)
const tableData = ref<ExecutionItem[]>([])
const detailDialogVisible = ref(false)
const extendDialogVisible = ref(false)
const closeDialogVisible = ref(false)
const currentPermit = ref<ExecutionItem | null>(null)

const searchForm = reactive({
  workType: '',
  location: '',
  status: ''
})

const pagination = reactive({
  page: 1,
  size: 10,
  total: 0
})

// 模拟数据
const mockData: ExecutionItem[] = [
  {
    id: 1,
    permitNumber: 'WP20250115001',
    workType: 'high_altitude',
    location: 'A区3楼外墙维修',
    applicant: '张三',
    startTime: '2025-01-16 08:00',
    endTime: '2025-01-16 17:00',
    status: 'executing',
    progress: 65,
    workContent: '外墙保温层维修，需要高空作业',
    safetyMeasures: ['佩戴安全帽', '系安全带', '配备灭火器'],
    personnel: [
      { name: '李四', type: '高空作业', certificateExpiry: '2025-12-31' }
    ],
    gasDetectors: [
      { name: '王五', role: '气测员', department: '安全部' }
    ]
  },
  {
    id: 2,
    permitNumber: 'WP20250115002',
    workType: 'hot_work',
    location: 'B区管道焊接',
    applicant: '赵六',
    startTime: '2025-01-17 09:00',
    endTime: '2025-01-17 15:00',
    status: 'preparing',
    progress: 20,
    workContent: '管道焊接作业，需要动火',
    safetyMeasures: ['配备灭火器', '气体检测', '隔离措施'],
    personnel: [
      { name: '钱七', type: '焊工', certificateExpiry: '2025-10-15' }
    ],
    gasDetectors: [
      { name: '孙八', role: '气测员', department: '安全部' }
    ]
  },
  {
    id: 3,
    permitNumber: 'WP20250115003',
    workType: 'electrical',
    location: '配电室设备检修',
    applicant: '周九',
    startTime: '2025-01-18 08:30',
    endTime: '2025-01-18 16:30',
    status: 'expiring',
    progress: 90,
    workContent: '配电室设备检修，需要停电作业',
    safetyMeasures: ['隔离措施', '气体检测', '佩戴安全帽'],
    personnel: [
      { name: '吴十', type: '电工', certificateExpiry: '2025-11-30' }
    ],
    gasDetectors: [
      { name: '郑十一', role: '安全员', department: '安全部' }
    ]
  }
]

// 获取执行列表
const fetchExecutions = async () => {
  try {
    loading.value = true
    
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 500))
    
    let filteredData = mockData
    
    // 根据筛选条件过滤
    if (searchForm.workType) {
      filteredData = filteredData.filter(item => item.workType === searchForm.workType)
    }
    
    if (searchForm.location) {
      filteredData = filteredData.filter(item => 
        item.location.includes(searchForm.location)
      )
    }
    
    if (searchForm.status) {
      filteredData = filteredData.filter(item => item.status === searchForm.status)
    }
    
    // 分页
    const start = (pagination.page - 1) * pagination.size
    const end = start + pagination.size
    
    tableData.value = filteredData.slice(start, end)
    pagination.total = filteredData.length
  } catch (error: any) {
    ElMessage.error(error.message || '获取执行列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.page = 1
  fetchExecutions()
}

// 重置
const handleReset = () => {
  searchForm.workType = ''
  searchForm.location = ''
  searchForm.status = ''
  pagination.page = 1
  fetchExecutions()
}

// 刷新列表
const refreshList = () => {
  fetchExecutions()
  ElMessage.success('刷新成功')
}

// 跳转到申请页面
const goToApply = () => {
  router.push('/permit/apply')
}

// 查看详情
const handleView = (row: ExecutionItem) => {
  currentPermit.value = row
  detailDialogVisible.value = true
}

// 申请延期
const handleExtend = (row: ExecutionItem) => {
  currentPermit.value = row
  extendDialogVisible.value = true
}

// 申请关闭
const handleClose = (row: ExecutionItem) => {
  currentPermit.value = row
  closeDialogVisible.value = true
}

// 从详情页延期
const handleExtendFromDetail = (permit: ExecutionItem) => {
  currentPermit.value = permit
  extendDialogVisible.value = true
}

// 从详情页关闭
const handleCloseFromDetail = (permit: ExecutionItem) => {
  currentPermit.value = permit
  closeDialogVisible.value = true
}

// 延期成功
const handleExtendSuccess = () => {
  fetchExecutions()
  ElMessage.success('延期申请提交成功')
}

// 关闭成功
const handleCloseSuccess = () => {
  fetchExecutions()
  ElMessage.success('关闭申请提交成功')
}

// 分页大小变化
const handleSizeChange = (size: number) => {
  pagination.size = size
  pagination.page = 1
  fetchExecutions()
}

// 当前页变化
const handleCurrentChange = (page: number) => {
  pagination.page = page
  fetchExecutions()
}

// 获取作业类型标签类型
const getWorkTypeTagType = (type: string) => {
  const typeMap: Record<string, string> = {
    high_altitude: 'warning',
    hot_work: 'danger',
    electrical: 'primary',
    confined_space: 'info',
    lifting: 'success'
  }
  return typeMap[type] || 'info'
}

// 获取作业类型标签
const getWorkTypeLabel = (type: string) => {
  const labelMap: Record<string, string> = {
    high_altitude: '高空作业',
    hot_work: '动火作业',
    electrical: '电气作业',
    confined_space: '受限空间',
    lifting: '起重作业'
  }
  return labelMap[type] || type
}

// 获取状态标签类型
const getStatusTagType = (status: string) => {
  const typeMap: Record<string, string> = {
    preparing: 'info',
    executing: 'success',
    paused: 'warning',
    expiring: 'danger'
  }
  return typeMap[status] || 'info'
}

// 获取状态标签
const getStatusLabel = (status: string) => {
  const labelMap: Record<string, string> = {
    preparing: '准备中',
    executing: '执行中',
    paused: '暂停',
    expiring: '即将超期'
  }
  return labelMap[status] || status
}

// 获取进度状态
const getProgressStatus = (progress: number) => {
  if (progress >= 100) return 'success'
  if (progress >= 80) return 'warning'
  return 'primary'
}

onMounted(() => {
  fetchExecutions()
})
</script>

<style lang="scss" scoped>
.permit-execution {
  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    
    h2 {
      margin: 0;
      color: #333;
    }
    
    .header-actions {
      display: flex;
      gap: 12px;
    }
  }
  
  .filter-card {
    margin-bottom: 20px;
  }
  
  .pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
}
</style>

